<?php

namespace App\Task;

use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\Playlet;
use App\Model\PlayletEpisodes;
use App\Model\PlayletEpisodesReplace;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class DyCheckDramaTask
{
    protected LoggerInterface $logger;

    public static $getTokenUrl = "https://open.douyin.com/oauth/client_token/";

    public static $getDramaUrl = "https://open.douyin.com/api/playlet/v2/album/fetch/";

    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'dycheckDrama');
    }

    public function execute()
    {
//        return;
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------开始定时获取剧目提审数据');
        $this->logger->info('获取短剧中提审的的数据');
        //获取需要获取任务的视频
        $playletData = Playlet::query()->where('album_id','!=',0)->whereNotIn('album_status',[0,3])->get();
        if($playletData->isNotEmpty()){

            $playletIds = [];

            foreach ($playletData as $playletDatum) {
                $playletIds[] = $playletDatum->id;
            }
            //查询关联表中的抖音小程序ID
            $this->logger->info('查询关联表中的抖音小程序ID,',$playletIds);
            $appletPlayletRelData = AppletPlayletRel::query()->whereIn('playlet_id',$playletIds)->where(['applet_id' => 20000])->select(['playlet_id','applet_id'])->orderBy('applet_id')->get();
            if($appletPlayletRelData->isNotEmpty()) {
                $appletIds = array();
                $appletPlayletKeyVal = array();
                //遍历获取对应关系和抖音小程序ID
                foreach ($appletPlayletRelData as $appletPlayletRelDatum){

                    $appletPlayletKeyVal[$appletPlayletRelDatum->playlet_id][] = $appletPlayletRelDatum->applet_id;
                    $appletIds[] = $appletPlayletRelDatum->applet_id;

                }
                $appletIds = array_values(array_unique($appletIds));
                //查询抖音小程序的ID 获取appID 和密钥
                $this->logger->info('查询抖音小程序的ID 获取appID 和密钥');
                $appletData = Applet::query()->whereIn('id',$appletIds)->where(['type' => 2])->select(['id','name','app_id','app_secret'])->get();
                if($appletData->isNotEmpty()) {

                    $appletKeyVal = [];
                    foreach ($appletData as $appletDatum) {
                        $appletKeyVal[$appletDatum->id] = $appletDatum;
                    }
                    foreach ($playletData as $playletDatum) {
                        //短剧名称
                        $playlet_name = $playletDatum->name;
                        $playletEpisodesData = PlayletEpisodes::query()->select(['id','playlet_number','playlet_number_name','open_video_id','dy_cloud_id','dy_episodes_id'])
                            ->where('playlet_id',$playletDatum->id)
                            ->where('is_dy_upload','!=',4)
                            ->where('dy_media_status','!=',3)->where('dy_cloud_id','!=',0)->get();

                        //获取对应的抖音小程序accessToken,获取这个短剧绑定的抖音小程序
                        if(empty($appletPlayletKeyVal[$playletDatum->id])){
                            continue;
                        }
                        $appletPlayletData = $appletPlayletKeyVal[$playletDatum->id];
                        $appletInfo = array();
                        foreach ($appletPlayletData as $appletPlayletDatum){
                            if(!empty($appletKeyVal[$appletPlayletDatum])){
                                $appletInfo = $appletKeyVal[$appletPlayletDatum];
                                break;
                            }
                        }
                        if(empty($appletInfo)){
                            $this->logger->error('获取绑定此短剧的抖音小程序不存在:');
                            continue;
                        }
                        $applet_name = $appletInfo->name;
                        $this->logger->info('获取绑定此短剧的抖音小程序token:'.$applet_name);
                        $accessToken = $this->getDyAccessToken($appletInfo->id,$appletInfo->app_id,$appletInfo->app_secret);
//                        $this->logger->info('获取短剧审核数据:'.$playlet_name);

                        if($playletEpisodesData->isNotEmpty() && !empty($appletInfo)) {

                            $episodesInfo = $this->getMeDiaInfo($playletDatum->album_id,$appletInfo->app_id,$accessToken,$playletDatum->album_version);
//                            var_dump(count($dramaInfo));

//                            $this->logger->info('开始遍历获取短剧剧集集数的审核数据',[$episodesInfo]);
                            if(!empty($episodesInfo)){
                                $this->logger->info('开始遍历获取短剧剧集集数的审核数据',[count($episodesInfo)]);
                                $dyepisodesKeyVal = array();
                                foreach ($episodesInfo as $episodes){
                                    $dyepisodesKeyVal[$episodes['seq']] = $episodes['episode_audit_info'];
                                }

                                if(!empty($dyepisodesKeyVal)){
                                    $this->logger->info('开始匹配短剧剧集集数的审核数据',[count($dyepisodesKeyVal)]);
                                    foreach ($playletEpisodesData as $playletEpisodes){
                                        //判断集数
                                        if(!empty($dyepisodesKeyVal[$playletEpisodes->playlet_number])){

                                            $episode_audit_info = $dyepisodesKeyVal[$playletEpisodes->playlet_number];
                                            //判断dy集数ID是否一致
                                            if($episode_audit_info['episode_id'] == $playletEpisodes->dy_episodes_id){

                                                if(!empty($episode_audit_info['audit_status'])){

                                                    if($episode_audit_info['audit_status'] == 1){

                                                        $playletEpisodes->dy_media_status = 4;
                                                        $playletEpisodes->is_dy_upload = 1;
                                                        $playletEpisodes->dy_media_status_error = $episode_audit_info['audit_msg'];
                                                        $playletEpisodes->save();
                                                    }
                                                    if($episode_audit_info['audit_status'] == 2){

                                                        //2023-12-25 新增判断是否在替换表中存在该短剧
                                                        $replaceInfo = PlayletEpisodesReplace::query()->where(['playlet_id' => $playletDatum->id,'playlet_episodes_ids' => $playletEpisodes->id,'type' => 2,'status' => 2])->first();
                                                        if(!empty($replaceInfo)){
                                                            $replaceInfo->status = 3;
                                                            $replaceInfo->save();
                                                        }
                                                        $playletEpisodes->dy_media_status = 3;
                                                        $playletEpisodes->save();
                                                    }
                                                    if($episode_audit_info['audit_status'] == 98){
                                                        $playletEpisodes->dy_media_status = 1;
                                                        $playletEpisodes->save();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                $this->logger->info('抖音小程序：'.$applet_name.' 短剧：'.$playlet_name.' 获取审核数据失败');
                            }
                        }else{
                            $this->logger->error('短剧没有绑定抖音小程序或者短剧没有需要审核的集数');
                        }
                    }
                }else{
                    $this->logger->error('查询抖音小程序ID：没有对应的抖音小程序数据');
                }
            }else{
                $this->logger->error('查询关联表中的抖音小程序ID：没有对应的短剧抖音小程序数据');
            }
        }else{
            $this->logger->info('没有短剧审核数据');
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取剧目提审数据');
    }
    public function getDyAccessToken($applet_id,$app_id,$app_secret){

        $container = ApplicationContext::getContainer();

        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('dy');

        $key = 'dy_admin_access_token';
        $key .= $applet_id;
        $accessToken = $redis->get($key);
        if(empty($accessToken)){
            $params         = [
                'grant_type' => 'client_credential',
                'client_key'    => $app_id,
                'client_secret'   => $app_secret
            ];
            //获取token
            $accessTokenInfo     = $this->request($params, self::$getTokenUrl,'POST');
            if (!empty($accessTokenInfo['data']['access_token'])){
                $accessToken = $accessTokenInfo['data']['access_token'];
                $redis->setex($key,7100,$accessToken);
            }else{
                $accessToken = "";
            }
        }
        $this->logger->info('抖音token为：'.$accessToken);
        return $accessToken;
    }

    public function getMeDiaInfo($album_id,$app_id,$accessToken,$version,$offset=0,$detail_data =array()){

        $params         = [
            "ma_app_id"   =>$app_id,
            "query_type"   => 3,
            "detail_query"    => [
                'album_id' => $album_id,
                "version" => $version,
                "offset" => $offset,
                "limit" => 50
            ]
        ];
        $taskUrl = self::$getDramaUrl;
        $this->logger->info('请求剧目集数信息数据：'.PHP_EOL.var_export(['result' => $params], true));
        $this->logger->info('请求剧目集数信息Url：'.$taskUrl);
        $postResult  = $this->request($params, $taskUrl,'POST',$accessToken);
        if($postResult['err_no'] == 0){
            //$this->logger->info('调用剧目集数信息接口成功 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
            $result = $postResult['data']['detail_data']['episode_info_list'];
            $count = $postResult['data']['detail_data']['total'];
            if($count == count($detail_data)){
                return $detail_data;
            }else{
                if(!empty($result)){
                   $detail_data = array_merge($result,$detail_data);

                   return $this->getMeDiaInfo($album_id,$app_id,$accessToken,$version,count($detail_data),$detail_data);
                }
            }
        }else{
            $this->logger->error('调用剧目集数信息接口失败 返回数据：'.PHP_EOL.var_export(['result' => $postResult], true));
        }
        return false;
    }
    /**
     * 传入数组进行HTTP POST请求
     */
    function request(array $params, string $url,string $method,string $access_token = null)
    {
        $client   = new Client([
            'timeout' => 3
        ]);
        $headers       = ['Content-Type' => 'application/json'];
        if(!empty($access_token)){
            $headers['access-token'] = $access_token;
        }

        $requestParams = [
            'headers' => $headers,
        ];
        if ($method == 'GET') {
            $requestParams['query'] = $params;
        } else {
            $requestParams['json'] = $params;//json_encode($params,JSON_UNESCAPED_UNICODE);
        }
        $response = $client->request($method,$url, $requestParams);
        if ($response->getStatusCode() !== 200) {
            return '';
        }
        $result   = $response->getBody()->getContents();
        $resultArr = json_decode($result,true);
        return $resultArr;

    }
}